package com.sinoglobal.sinostore.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;
import com.sinoglobal.sinostore.R;
import com.sinoglobal.sinostore.StateBaseActivity;
import com.sinoglobal.sinostore.bean.AddressVo;
import com.sinoglobal.sinostore.bean.FreightVo;
import com.sinoglobal.sinostore.bean.GoodsDetailsVo;
import com.sinoglobal.sinostore.bean.ShipMethodVo;
import com.sinoglobal.sinostore.bean.SubmitOrderVo;
import com.sinoglobal.sinostore.dialog.SweetAlertDialog;
import com.sinoglobal.sinostore.dialog.SweetAlertDialog.OnSweetClickListener;
import com.sinoglobal.sinostore.listener.OnAntiViolenceClickListener;
import com.sinoglobal.sinostore.system.Constants;
import com.sinoglobal.sinostore.utils.ApiDebugUtil;
import com.sinoglobal.sinostore.utils.BitmapHelp;
import com.sinoglobal.sinostore.utils.SharedPreferenceUtil;
import com.sinoglobal.sinostore.utils.SignUtil;
import com.sinoglobal.sinostore.utils.TextUtil;

/**
 * 
 * @title: SubmitOrderFormActivity.java
 * @package com.chiliring.sinostore.activity
 * @description: TODO(确认订单)
 * @author LK
 * @date 2015-1-15 下午7:32:36
 */
public class SubmitOrderFormActivity extends StateBaseActivity {
	/** 订单是否提交 **/
	private boolean isSubmitOrder = false;
	private int submit_type; // 1 自取 2快递
	private LinearLayout submitorderformKd; // 快递的view
	private TextView shopMinus; // "-" 数量
	private EditText shopNums; // 总数量
	private TextView shopPlus; // "+" 数量
	private int shopnum = 1; // 添加的数量
	private TextView shopDetailBtnDh; // 提交订单按钮
	private GoodsDetailsVo goodsDetailsVo; // 产品id
	/** 标记配送方式 **/
	public static int oldposition = 0;
	/** 标记发票 **/
	public static int invoicePosition = 0;
	/** 发票类型 0 个人 1单位 **/
	public static int isPersonalOrCompany = 0;
	/** 商品图片 **/
	private ImageView imgGoodsPic; // 商品图
	/** 商品名称 **/
	private TextView tvGoodsName; // 商品名称
	private TextView shopDetailTotalPrice;
	/** 商品价格 **/
	private TextView tvGoodsPrice;
	private TextView tvAddressName; // 收获地址姓名
	private TextView tvAddress;// 收获地址信息
	private TextView tvAddressPhone; // 收获电话
	private TextView noAddress; // 无收获地址
	private TextView tvFreight;// 运费
	/** 用户收货地址 **/
	private RelativeLayout rlShopAddress;
	private SubmitOrderVo submitOrderVo;// 提交订单响应返回
	private RelativeLayout shipMethod;// 配送方式

	/** 发票信息 **/
	private TextView tvInvoicein;

	/** 发票信息 **/
	private RelativeLayout rlInvoiceInfo;

	private String rsa_yunfei = "0";// 运费密文
	private String shipType = "";// 运费类型
	private ShipMethodVo methodVo;

	public static final int ISAddRESS = 120;
	public static final int NOAddRESS = 130;
	public static final int SHIPMETHOD = 140;
	/** 发票信息 **/
	public static final int INVOICECODE = 150;

	private AddressVo addressVo = null;// 收货地址对象

	private BitmapUtils bitmapUtils;

	/** 发票类型 **/
	private String invoiceType = "";
	/** 发票抬头 **/
	private String invoiceLookUp = "";
	/** 商品种类 **/
	private String goodsTypeName = "";
	/** 买家留言 **/
	private EditText etNote;
	/** 配置订单信息 **/
	private LinearLayout llDetailsInfo;
	/** 秒杀订单签名 **/
	private String msSign;

	private String mySign;

	/** 支付方式 **/
	private int payType;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		titleView.setText("提交订单");
		setContentView(R.layout.shop_activity_confirm_order);
		openChenJInShi();
		initView();
		initData();
	}

	private void initData() {
		Intent intent = getIntent();
		if (intent != null) {
			goodsDetailsVo = (GoodsDetailsVo) intent.getSerializableExtra("goodsDetail");
			msSign = intent.getStringExtra("msSign");
			mySign = intent.getStringExtra("mySign");
		}
		bitmapUtils = BitmapHelp.getBitmapUtils(this);
		// 虚拟商品
		if (Constants.VIRTUALGOODS.equals(goodsDetailsVo.type)) {
			submitorderformKd.setVisibility(View.GONE);
			llDetailsInfo.setVisibility(View.GONE);
		} else {
			loadDefaultAddress();
			submitorderformKd.setVisibility(View.VISIBLE);
			llDetailsInfo.setVisibility(View.VISIBLE);
		}
		// msSign不为空说明下订单为抢购商品，限购一件
		if (!TextUtils.isEmpty(msSign)) {
			shopMinus.setClickable(false);
			shopMinus.setTextColor(getResources().getColor(R.color.text_hint));
			shopNums.setKeyListener(null);
			shopPlus.setClickable(false);
			shopPlus.setTextColor(getResources().getColor(R.color.text_hint));
		}
		// 设置提交页面内容
		setSubmitInfo();

	}

	/**
	 * 
	 * @author czz
	 * @createdate 2014-9-19 上午10:14:14
	 * @Description: (设置提交页面内容)
	 */
	private void setSubmitInfo() {
		tvGoodsName.setText(goodsDetailsVo.name);
		bitmapUtils.display(imgGoodsPic, goodsDetailsVo.getHost() + goodsDetailsVo.img_url);
		// 如果在秒杀时间内使用秒杀价格
		if (Constants.ISMS == goodsDetailsVo.is_ms) {
			tvGoodsPrice.setText(String.format("现金%s元", goodsDetailsVo.ms_price));
			shopDetailTotalPrice.setText(String.format("现金%s元", goodsDetailsVo.ms_price));
			// 支付方式
			payType = Constants.MONEYPAY;
		} else {
			if (TextUtil.isZeroOrNull(goodsDetailsVo.price) && !TextUtil.isZeroOrNull(goodsDetailsVo.cash)) {// 积分单价为零，现金不为零，为现金支付
				tvGoodsPrice.setText(String.format("现金%s元", goodsDetailsVo.cash));
				shopDetailTotalPrice.setText(String.format("现金%s元", goodsDetailsVo.cash));
				// 现金支付
				payType = Constants.MONEYPAY;
			} else if (TextUtil.isZeroOrNull(goodsDetailsVo.cash) && !TextUtil.isZeroOrNull(goodsDetailsVo.price)) {// 现金单价为零，为积分支付
				tvGoodsPrice.setText(String.format("%s%s", goodsDetailsVo.price, getString(R.string.score_unit)));
				shopDetailTotalPrice.setText(String.format("%s%s", goodsDetailsVo.price, getString(R.string.score_unit)));
				// 积分支付
				payType = Constants.SCOREPAY;
			} else {// 两个都不为零则为现金加积分支付
				tvGoodsPrice
						.setText(String.format("现金%s元+%s%s", goodsDetailsVo.cash, goodsDetailsVo.price, getString(R.string.score_unit)));
				shopDetailTotalPrice.setText(String.format("现金%s元+%s%s", goodsDetailsVo.cash, goodsDetailsVo.price,
						getString(R.string.score_unit)));
				// 现金支付
				payType = Constants.MONEYPAY;
			}
		}

		if (!TextUtils.isEmpty(goodsDetailsVo.freight)) {
			rsa_yunfei = goodsDetailsVo.freight;
		}

		if (null != goodsDetailsVo.ys_type && goodsDetailsVo.ys_type.size() > 0) {
			shipMethod.setClickable(true);
			methodVo = goodsDetailsVo.ys_type.get(0);
			shipType = methodVo.getCode();
			if (Constants.ISSELF_CODE.equals(shipType)) {
				tvFreight.setText(String.format("%s", "上门自取"));
				submit_type = 1;
			} else if (Constants.PACKAGEMAIL.equals(shipType)) {
				tvFreight.setText("包邮");
				submit_type = 2;
				if (goodsDetailsVo.ys_type.size() <= 1) {
					shipMethod.setClickable(false);
				}
			} else {
				tvFreight.setText(String.format("%s %s元", methodVo.getName(), methodVo.getCost()));
				submit_type = 2;
			}
		} else {
			shipMethod.setClickable(false);
			tvFreight.setText(String.format("%s元", "0.00"));
		}
	}

	/**
	 * 
	 * @author czz
	 * @createdate 2014-9-18 下午7:53:49
	 * @Description: (获取默认收货地址)
	 * 
	 */
	private void loadDefaultAddress() {
		HttpUtils httpUtils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("por", "5004");
		params.addQueryStringParameter("proIden", Constants.STOREFLAG);
		params.addQueryStringParameter("user_id", Constants.userCenterId);
		httpUtils.send(HttpMethod.POST, Constants.STORE_URL, params, new RequestCallBack<String>() {
			@Override
			public void onFailure(HttpException arg0, String arg1) {

			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String result = responseInfo.result;
				if (!TextUtils.isEmpty(result)) {
					AddressVo address = JSON.parseObject(result, AddressVo.class);
					if (Constants.STORE_SUCCESS_CODE.equals(address.getCode())) {
						if (null != address.getAddress()) {
							noAddress.setVisibility(View.GONE);
							rlShopAddress.setVisibility(View.VISIBLE);
							addressVo = address;
							setDefAddress(address);
						} else {
							noAddress.setVisibility(View.VISIBLE);
							rlShopAddress.setVisibility(View.GONE);
						}
					}
				}
			}
		});
	}

	/**
	 * 
	 * @author czz
	 * @param result
	 * @createdate 2014-9-19 上午10:46:05
	 * @Description: (设置默认收获地址)
	 * 
	 */
	private void setDefAddress(AddressVo result) {
		noAddress.setVisibility(View.GONE);
		rlShopAddress.setVisibility(View.VISIBLE);
		tvAddressName.setText(result.getConnect_name());
		tvAddress.setText(result.getArea() + result.getAddress());
		tvAddressPhone.setText(result.getConnect_tel());
		// 非上门自取或包邮的商品需要请求邮费
		if (!Constants.ISSELF_CODE.equals(shipType) && !Constants.PACKAGEMAIL.equals(shipType)) {
			getFreight(shopnum, addressVo, shipType);
		}
	}

	public void initView() {
		tvFreight = (TextView) this.findViewById(R.id.tvfreight);
		submitorderformKd = (LinearLayout) findViewById(R.id.submitorderform_kd);
		shopDetailBtnDh = (TextView) findViewById(R.id.submit);
		shopDetailTotalPrice = (TextView) findViewById(R.id.shop_detail_tv_bi);
		shopMinus = (TextView) findViewById(R.id.shop_minus);
		shopNums = (EditText) findViewById(R.id.shop_nums);
		shopPlus = (TextView) findViewById(R.id.shop_plus);
		tvGoodsPrice = (TextView) findViewById(R.id.tv_goods_price);
		imgGoodsPic = (ImageView) findViewById(R.id.im_goods_pic);
		tvGoodsName = (TextView) findViewById(R.id.tv_goods_name);
		rlInvoiceInfo = (RelativeLayout) findViewById(R.id.rl_invoice_info);

		tvAddressName = (TextView) findViewById(R.id.tv_address_name);
		tvAddress = (TextView) findViewById(R.id.tv_address);
		tvAddressPhone = (TextView) findViewById(R.id.tv_address_phone);
		shipMethod = (RelativeLayout) this.findViewById(R.id.ship_method);
		llDetailsInfo = (LinearLayout) this.findViewById(R.id.ll_goods_info);

		noAddress = (TextView) findViewById(R.id.tv_noaddress);
		rlShopAddress = (RelativeLayout) findViewById(R.id.rela_address);
		etNote = (EditText) this.findViewById(R.id.et_leavemessage);
		tvInvoicein = (TextView) this.findViewById(R.id.tv_invoicein);

		shopMinus.setOnClickListener(clickListener);
		shopPlus.setOnClickListener(clickListener);
		submitorderformKd.setOnClickListener(clickListener);
		shipMethod.setOnClickListener(clickListener);
		rlInvoiceInfo.setOnClickListener(clickListener);
		shopDetailBtnDh.setOnClickListener(clickListener);

		templateButtonLeft.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				cancelOrder();
			}
		});
		shopNums.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				int available = -1;// 用户还能购买数 -1 未限购
				int buyNum = 99;
				int restriction = 0;
				if (!TextUtils.isEmpty(goodsDetailsVo.available)) {
					available = Integer.parseInt(goodsDetailsVo.available);
				}
				if (!TextUtils.isEmpty(goodsDetailsVo.restriction)) {
					restriction = Integer.parseInt(goodsDetailsVo.restriction);
				}
				if (available > -1 && restriction > 0) {
					buyNum = available;
				}
				if (!Constants.VIRTUALGOODS.equals(goodsDetailsVo.type) && submit_type == 2 && TextUtils.isEmpty(goodsDetailsVo.type)) {
					if (null == addressVo) {
						showShortToast(getResources().getString(R.string.noaddress));
						return;
					}
				}
				if (TextUtils.isEmpty(shopNums.getText().toString().trim())) {
					shopnum = 1;
					shopNums.setText(String.valueOf(1));
				} else {
					try {
						shopnum = Integer.parseInt(shopNums.getText().toString());
					} catch (Exception e) {
						shopnum = 1;
					}
				}
				if (shopnum < 1) {
					shopnum = 1;
					shopNums.setText(String.valueOf(shopnum));
				} else if (shopnum > 99) {
					showShortToast("已超过最大购买数");
					shopnum = 99;
					shopNums.setText(String.valueOf(shopnum));
				}
				getFreight(shopnum, addressVo, shipType);// 计算运费
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
	}

	/** 反暴力点击 **/
	private OnAntiViolenceClickListener clickListener = new OnAntiViolenceClickListener() {
		@Override
		public void onAVClick(View v) {
			Intent intent = null;
			int available = -1;// 用户还能购买数 -1 未限购
			int buyNum = 99;
			int restriction = 0;
			if (!TextUtils.isEmpty(goodsDetailsVo.available)) {
				available = Integer.parseInt(goodsDetailsVo.available);
			}
			if (!TextUtils.isEmpty(goodsDetailsVo.restriction)) {
				restriction = Integer.parseInt(goodsDetailsVo.restriction);
			}
			if (available > -1 && restriction > 0) {
				buyNum = available;
			}
			int id = v.getId();
			if (id == R.id.shop_minus) {
				if (!Constants.VIRTUALGOODS.equals(goodsDetailsVo.type) && submit_type == 2) {
					if (null == addressVo) {
						showShortToast(getResources().getString(R.string.noaddress));
						return;
					}
				}
				try {
					shopnum = Integer.parseInt(shopNums.getText().toString());
				} catch (Exception e) {
					shopnum = 1;
				}
				if (shopnum == 1) {
					return;
				}
				shopNums.setText((shopnum -= 1) >= 1 ? shopnum + "" : "1");
			} else if (id == R.id.shop_plus) {
				if (!Constants.VIRTUALGOODS.equals(goodsDetailsVo.type) && submit_type == 2) {
					if (null == addressVo) {
						showShortToast(getResources().getString(R.string.noaddress));
						return;
					}
				}
				try {
					shopnum = Integer.parseInt(shopNums.getText().toString());
				} catch (Exception e) {
					shopnum = 99;
				}
				if (shopnum == 99) {
					return;
				}
				if (shopnum >= buyNum && restriction > 0) {// restriction
					if (available > 0) {
						showShortToast(String.format("宝贝限购%s件哦,您已经买了%s件了", restriction, restriction - available));
					} else {
						showShortToast("超出限购啦\n您不能买这么多啊亲");
					}
					return;
				}
				shopNums.setText((shopnum += 1) <= 99 ? shopnum + "" : "99");
			} else if (id == R.id.submit) {
				// 提交订单
				submitOrder();
			} else if (id == R.id.submitorderform_kd) {
				intent = new Intent(SubmitOrderFormActivity.this, AddressListActivity.class);
				if (null != addressVo) {
					intent.putExtra("addressId", addressVo.getId());
				}
				intent.putExtra("orderSubmit", AddressListActivity.ORDER);
				startActivityForResult(intent, ISAddRESS);
				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
			} else if (id == R.id.ship_method) {
				if (submit_type == 1 || null != addressVo) {
					intent = new Intent(SubmitOrderFormActivity.this, ShippingMethodActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("shipList", goodsDetailsVo.ys_type);
					bundle.putString("goodsId", goodsDetailsVo.id);
					bundle.putString("shopId", goodsDetailsVo.shop_id);
					bundle.putString("pId", goodsDetailsVo.p_id);
					bundle.putString("isSelf", goodsDetailsVo.is_self);
					intent.putExtras(bundle);
					startActivityForResult(intent, SHIPMETHOD);
					overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
				} else {
					showShortToast(getResources().getString(R.string.noaddress));
				}
			} else if (id == R.id.rl_invoice_info) {
				if (!TextUtil.isZeroOrNull(goodsDetailsVo.cash)
						|| (Constants.ISMS == goodsDetailsVo.is_ms && !TextUtils.isEmpty(goodsDetailsVo.ms_price))) {
					intent = new Intent(SubmitOrderFormActivity.this, InvoiceActivity.class);
					intent.putExtra("invoiceLookUp", invoiceLookUp);
					startActivityForResult(intent, INVOICECODE);
				} else {
					showShortToast("仅现金购买的商品提供发票");
				}
			} else {
			}
		}
	};

	// 取消订单
	private void cancelOrder() {
		if (Constants.ISMS == goodsDetailsVo.is_ms) {
			sendBroad();
			final SweetAlertDialog alertDialog = new SweetAlertDialog(SubmitOrderFormActivity.this);
			alertDialog.showCancelButton(true);
			alertDialog.setTitleText("确认取消该订单？");
			alertDialog.setContentText("");
			alertDialog.setCancelText("取消");
			alertDialog.setConfirmText("确定");
			alertDialog.setConfirmClickListener(new OnSweetClickListener() {
				@Override
				public void onClick(SweetAlertDialog sweetAlertDialog) {
					alertDialog.dismiss();
					SubmitOrderFormActivity.this.finish();
				}
			});
			alertDialog.show();
		} else {
			SubmitOrderFormActivity.this.finish();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			cancelOrder();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 
	 * @author lk
	 * @createdate 2014-9-19 下午2:54:35
	 * @Description: (提交订单)
	 * 
	 */
	private void submitOrder() {
		if (!isSubmitOrder) {
			final String address = tvAddress.getText().toString().trim();// 收货地址
			final String connent_name = tvAddressName.getText().toString().trim();// 联系人姓名
			final String connent_phone = tvAddressPhone.getText().toString().trim();// 联系电话
			// 判断库存
			if ("0".equals(goodsDetailsVo.nums)) {
				showShortToast(getResources().getString(R.string.shop_kc_4));
				return;
			}
			if (shopnum > Integer.parseInt(goodsDetailsVo.nums) && TextUtil.stringIsNotNull(goodsDetailsVo.nums)) {
				showShortToast(getResources().getString(R.string.shop_kc_5));
				return;
			}

			if (shopnum > Integer.parseInt(goodsDetailsVo.available) && Integer.parseInt(goodsDetailsVo.available) > -1
					&& Integer.parseInt(goodsDetailsVo.restriction) > 0) {
				if (Integer.parseInt(goodsDetailsVo.available) > 0) {
					int restriction = Integer.parseInt(goodsDetailsVo.restriction);
					int available = Integer.parseInt(goodsDetailsVo.available);
					showShortToast(String.format("宝贝限购%s件哦,您已经买了%s件了", restriction, restriction - available));
				} else {
					showShortToast("超出限购啦\n您不能买这么多啊亲");
				}
				return;
			}

			if (submit_type == 2 && Constants.PHYSICAL.equals(goodsDetailsVo.type) && TextUtil.stringIsNull(address)
					&& TextUtil.stringIsNull(connent_name) && TextUtil.stringIsNull(connent_phone)) {
				showShortToast(getResources().getString(R.string.noaddress));
				return;
			}
			// 判断辣椒币
			// if(!TextUtils.isEmpty(goodsDetailsVo.price) &&
			// TextUtils.isEmpty(goodsDetailsVo.ms_price)){
			// int totalPrice = shopnum * (int)
			// Math.ceil(Double.parseDouble(goodsDetailsVo.price));
			// if(TextUtils.isEmpty(Constants.score)){
			// Constants.score = "0";
			// }
			// if (Integer.parseInt(Constants.score) < totalPrice) {
			// showShortToast(getResources().getString(R.string.outofcash));
			// return;
			// }
			// }
			final ProgressDialog dialog = new ProgressDialog(SubmitOrderFormActivity.this);
			dialog.show();
			String note = etNote.getText().toString();
			RequestParams params = new RequestParams();
			params.addQueryStringParameter("por", "202");
			params.addQueryStringParameter("proIden", Constants.STOREFLAG);
			params.addQueryStringParameter("user_id", Constants.userCenterId);
			params.addQueryStringParameter("user_name", Constants.userName);
			params.addQueryStringParameter("goods_id", goodsDetailsVo.id);// 商品id
			params.addQueryStringParameter("goods_nums", String.valueOf(shopnum));// 购买数量
			params.addQueryStringParameter("draw_type", String.valueOf(submit_type));// 领取方式
			params.addQueryStringParameter("pay_type", "1");// 支付方式
			if (!TextUtils.isEmpty(address)) {
				params.addQueryStringParameter("address", address);// 收货地址
			}
			if (!TextUtils.isEmpty(connent_name)) {
				params.addQueryStringParameter("connect_name", connent_name);// 联系人
			}
			if (!TextUtils.isEmpty(connent_phone)) {
				params.addQueryStringParameter("connect", connent_phone);// 联系电话
			}
			if (!TextUtils.isEmpty(msSign)) {
				params.addQueryStringParameter("ms_sign", msSign);// 秒杀数据签名
			}
			if (!TextUtils.isEmpty(mySign)) {
				params.addQueryStringParameter("my_sign", mySign);// 秒杀数据签名
			}
			params.addQueryStringParameter("order_time", String.valueOf(System.currentTimeMillis()));
			params.addQueryStringParameter("channel", SharedPreferenceUtil.getString(getApplicationContext(), "channel"));// 发票类型
			params.addQueryStringParameter("invoice_type", invoiceType);// 发票类型
			params.addQueryStringParameter("invoice_title", invoiceLookUp);// 发票抬头
			params.addQueryStringParameter("invoice_category", goodsTypeName);// 发票分类
			params.addQueryStringParameter("rsa_yunfei", rsa_yunfei);
			if (!TextUtils.isEmpty(note)) {
				params.addQueryStringParameter("note", note);// 备注
			}
			params.addQueryStringParameter("sign", SignUtil.generateSign(params));// 签名
			ApiDebugUtil.debug(params);
			HttpUtils httpUtils = new HttpUtils();
			httpUtils.send(HttpMethod.POST, Constants.STORE_URL, params, new RequestCallBack<String>() {

				@Override
				public void onStart() {
					super.onStart();
					LogUtils.i("请求路径" + this.getRequestUrl());
				}

				@Override
				public void onFailure(HttpException arg0, String arg1) {
					try {
						dialog.dismiss();
					} catch (Exception e) {
					}
					LogUtils.i(arg0.getMessage());
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					try {
						dialog.dismiss();
					} catch (Exception e) {
					}
					String result = responseInfo.result;
					LogUtils.i("result>>>>" + result);
					if (!TextUtils.isEmpty(result)) {
						SubmitOrderVo orderVo = JSON.parseObject(result, SubmitOrderVo.class);
						if (null == orderVo) {
							showShortToast(getResources().getString(R.string.orderfailed));
							return;
						}
						if (Constants.STORE_SUCCESS_CODE.equals(orderVo.getCode())) {
							// 订单提交成功
							isSubmitOrder = true;
							sendBroad();
							// 下订单成功修改本地库存
							if (TextUtil.stringIsNotNull(goodsDetailsVo.nums)) {
								int num = Integer.parseInt(goodsDetailsVo.nums) - shopnum;
								goodsDetailsVo.nums = String.valueOf(num);
							}
							submitOrderVo = orderVo;
							toPayforSuccess();
						}else if("8".equals(orderVo.getCode())){
							showShortToast("被抢光了...\n去看看其他商品吧");
						}else if("30".equals(orderVo.getCode())){
							showShortToast("订单超时，请重新购买");
						}else{
							showShortToast(orderVo.getMessage());
						}
					}
				}
			});
		} else {
			toPayforSuccess();
		}
	}

	private void toPayforSuccess() {
		// 订单已提交跳转提交成功页
		Intent intent = new Intent(SubmitOrderFormActivity.this, PayforActivity.class);
		intent.putExtra("orderNum", submitOrderVo.getOrder_num());
		intent.putExtra("goodsName", goodsDetailsVo.name);
		intent.putExtra("goodsType", goodsDetailsVo.type);
		intent.putExtra("goodsImg", goodsDetailsVo.img_url);
		intent.putExtra("payType", payType);
		intent.putExtra("submitType", String.valueOf(submit_type));
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
		SubmitOrderFormActivity.this.finish();
	}

	/** 发送广播 **/
	private void sendBroad() {
		Intent intent = new Intent(); //
		intent.setAction("com.gasFragment");
		intent.putExtra("reloading", true);
		sendBroadcast(intent); // 发送广播
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (SubmitOrderFormActivity.ISAddRESS == resultCode) {
			if (data != null) {
				addressVo = (AddressVo) data.getSerializableExtra(AddressListActivity.ADDRESS);
				setDefAddress(addressVo);
			}
			// 配送方式
		} else if (SHIPMETHOD == requestCode && requestCode == resultCode) {
			if (null != data) {
				methodVo = (ShipMethodVo) data.getSerializableExtra("methodVo");
				shipType = methodVo.getCode();
				getFreight(shopnum, addressVo, shipType);
			}
			// 发票信息
		} else if (INVOICECODE == requestCode && requestCode == resultCode) {
			if (null != data) {
				invoiceType = data.getStringExtra("invoiceType");
				invoiceLookUp = data.getStringExtra("invoiceLookUp");
				goodsTypeName = data.getStringExtra("goodsTypeName");
				tvInvoicein.setText(String.valueOf(invoiceLookUp));
			} else {
				tvInvoicein.setText("不开发票");
			}
		}
	}

	/**
	 * 
	 * @author LK
	 * @methods getFreight
	 * @description 描述信息 获取邮费
	 * @date 2014-12-13 下午4:35:11 参数说明
	 */
	@SuppressWarnings("unchecked")
	private void getFreight(int num, AddressVo addressVo, String shipType) {
		// 如果是选择自取
		if (Constants.ISSELF_CODE.equals(shipType) || Constants.PACKAGEMAIL.equals(shipType)) {
			rsa_yunfei = "0";
			if (Constants.ISSELF_CODE.equals(shipType)) {
				submit_type = 1;
				tvFreight.setText(String.format("%s", "上门自取"));
			} else {
				tvFreight.setText(String.format("%s", "包邮"));
				submit_type = 2;
			}
			double money = 0.0;
			int jifen = 0;
			if (Constants.ISMS == goodsDetailsVo.is_ms) {
				money = shopnum * Double.parseDouble(goodsDetailsVo.ms_price);
				shopDetailTotalPrice.setText(String.format("合计：%.2f元", money));
				// 现金支付
				payType = Constants.MONEYPAY;
			} else {
				if (TextUtil.isZeroOrNull(goodsDetailsVo.price) && !TextUtil.isZeroOrNull(goodsDetailsVo.cash)) {// 积分单价为零，现金不为零，为现金支付
					money = shopnum * Double.parseDouble(goodsDetailsVo.cash);
					shopDetailTotalPrice.setText(String.format("合计：%.2f元", money));
					// 现金支付
					payType = Constants.MONEYPAY;
				} else if (TextUtil.isZeroOrNull(goodsDetailsVo.cash) && !TextUtil.isZeroOrNull(goodsDetailsVo.price)) {// 现金单价为零，为积分支付
					jifen = shopnum * Integer.parseInt(goodsDetailsVo.price);
					shopDetailTotalPrice.setText(String.format("合计：%s%s", jifen, getString(R.string.score_unit)));
					// 积分支付
					payType = Constants.SCOREPAY;
				} else {// 两个都不为零则为现金加积分支付
					money = shopnum * Double.parseDouble(goodsDetailsVo.cash);
					jifen = shopnum * Integer.parseInt(goodsDetailsVo.price);
					shopDetailTotalPrice.setText(String.format("合计：%.2f元+%s%s", money, jifen, getString(R.string.score_unit)));
					// 现金支付
					payType = Constants.MONEYPAY;
				}
			}
		} else {
			if (null == addressVo) {
				showShortToast(getResources().getString(R.string.noaddress));
				return;
			}
			// 领取方式 1 自取 2 快递
			submit_type = 2;
			final ProgressDialog dialog = new ProgressDialog(this);
			try {
				dialog.show();
			} catch (Exception e) {
			}
			RequestParams params = new RequestParams();
			params.addQueryStringParameter("proIden", Constants.STOREFLAG);
			params.addQueryStringParameter("por", "107");
			params.addQueryStringParameter("id", goodsDetailsVo.id);
			params.addQueryStringParameter("num", String.valueOf(num));
			params.addQueryStringParameter("type", shipType);
			params.addQueryStringParameter("address", addressVo.getArea());
			params.addQueryStringParameter("sign", SignUtil.generateSign(params));
			HttpUtils httpUtils = new HttpUtils();
			httpUtils.send(HttpMethod.POST, Constants.STORE_URL, params, new RequestCallBack<String>() {
				@Override
				public void onStart() {
					super.onStart();
					LogUtils.i(">>>>url==" + this.getRequestUrl());
				}

				@Override
				public void onFailure(HttpException arg0, String arg1) {
					try {
						dialog.dismiss();
					} catch (Exception e) {
					}
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					try {
						dialog.dismiss();
					} catch (Exception e) {
					}
					String result = responseInfo.result;
					LogUtils.i(">>>>>>>>>>>>>>result=" + result);
					if (!TextUtils.isEmpty(result)) {
						FreightVo freightVo = JSON.parseObject(result, FreightVo.class);
						if (Constants.STORE_SUCCESS_CODE.equals(freightVo.getCode())) {
							if (!TextUtils.isEmpty(freightVo.getRsa_yunfei())) {
								rsa_yunfei = freightVo.getRsa_yunfei();
							}
							double freight = 0.0;
							if (!TextUtil.isZeroOrNull(freightVo.getFreight())) {
								freight = Double.parseDouble(freightVo.getFreight());
							}
							if (null != methodVo) {
								tvFreight.setText(String.format("%s %.2f元", methodVo.getName(), freight));
							} else {
								tvFreight.setText(String.format("%s元", "0.00"));
							}
							double money = 0.0;
							int jifen = 0;
							if (Constants.ISMS == goodsDetailsVo.is_ms) {
								money = shopnum * Double.parseDouble(goodsDetailsVo.ms_price);
								if (!TextUtil.isZeroOrNull(freightVo.getFreight())) {
									money += Double.parseDouble(freightVo.getFreight());
								}
								// 现金支付
								payType = Constants.MONEYPAY;
								shopDetailTotalPrice.setText(String.format("合计：%.2f元", money));
							} else {
								if (TextUtil.isZeroOrNull(goodsDetailsVo.price) && !TextUtil.isZeroOrNull(goodsDetailsVo.cash)) {// 积分单价为零，现金不为零，为现金支付
									money = shopnum * Double.parseDouble(goodsDetailsVo.cash);
									if (!TextUtil.isZeroOrNull(freightVo.getFreight())) {
										money += Double.parseDouble(freightVo.getFreight());
									}
									shopDetailTotalPrice.setText(String.format("合计：%.2f元", money));
									// 现金支付
									payType = Constants.MONEYPAY;
								} else if (TextUtil.isZeroOrNull(goodsDetailsVo.cash) && !TextUtil.isZeroOrNull(goodsDetailsVo.price)
										&& TextUtil.isZeroOrNull(freightVo.getFreight())) {// 现金单价为零，为积分支付
									jifen = shopnum * Integer.parseInt(goodsDetailsVo.price);
									shopDetailTotalPrice.setText(String.format("合计：%s%s", jifen, getString(R.string.score_unit)));
									// 积分支付
									payType = Constants.SCOREPAY;
								} else {// 两个都不为零则为现金加积分支付
									money = shopnum * Double.parseDouble(goodsDetailsVo.cash);
									if (!TextUtil.isZeroOrNull(freightVo.getFreight())) {
										money += Double.parseDouble(freightVo.getFreight());
									}
									jifen = shopnum * Integer.parseInt(goodsDetailsVo.price);
									shopDetailTotalPrice.setText(String.format("合计：%.2f元+%s%s", money, jifen,
											getString(R.string.score_unit)));
									// 现金支付
									payType = Constants.MONEYPAY;
								}
							}
						} else {
							showShortToast("获取运费失败");
						}
					}
				}
			});
		}
	}

	/***
	 * 
	 * @author LK
	 * @methods getUserInfo
	 * @description 描述信息 获取用户信息
	 * @date 2015-1-31 下午6:36:13 参数说明
	 */
	// private void getUserInfo(){
	// HttpUtils httpUtils = new HttpUtils();
	// String URL =
	// "http://hpyuserapp.sinosns.cn/customer/customer_getCustomerInfoById.action";
	// Map<String,Object> param = new HashMap<String,Object>();
	// param.put("ucenterId", FlyApplication.ucenterId);
	// param.put("customerId", FlyApplication.user_id);
	// String json = JSON.toJSONString(param);
	// List<NameValuePair> nvps = new ArrayList<NameValuePair>();
	// nvps.add(new BasicNameValuePair("json", json == null ? null : json));
	// RequestParams params = new RequestParams();
	// try {
	// params.setBodyEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
	// } catch (UnsupportedEncodingException e1) {
	// // TODO Auto-generated catch block
	// e1.printStackTrace();
	// }
	// httpUtils.send(HttpMethod.POST, URL ,params, new
	// RequestCallBack<String>() {
	// @Override
	// public void onStart() {
	// super.onStart();
	// LogUtils.i(">>>>>>>getRequestUrl"+this.getRequestUrl());
	// }
	// @Override
	// public void onFailure(HttpException arg0, String arg1) {
	// }
	// @Override
	// public void onSuccess(ResponseInfo<String> responseInfo) {
	// String result = responseInfo.result;
	// LogUtils.i("RESULT==="+result);
	// if(!TextUtils.isEmpty(result)){
	// try {
	// CustomerInfoVo infoVo = JSON.parseObject(result, CustomerInfoVo.class);
	// if("0000".equals(infoVo.getRescode())){
	// FlyApplication.integral = infoVo.getIntegral();
	// }
	// } catch (Exception e) {
	// }
	// }
	// }
	// });
	// }

	@Override
	protected void onDestroy() {
		super.onDestroy();
		/** 标记配送方式 **/
		oldposition = 0;
		/** 标记发票 **/
		invoicePosition = 0;
		/** 发票类型 0 个人 1单位 **/
		isPersonalOrCompany = 0;

		Constants.selectAddress = 0;
	}
}
